﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;
using System.Windows.Forms;

namespace SdmxMl.Helper
{
    public class XmlValidator
    {
        // Validation Error Count
        int ErrorsCount = 0;
        int maxErrorCount = 5;
        // Validation Error Message
        string ErrorMessage = "";
        string WarningMessage = "";

        public void ValidationHandler(object sender,
                                             ValidationEventArgs args)
        {
            switch (args.Severity)
            {
                case XmlSeverityType.Error:
                    if (ErrorsCount == maxErrorCount)
                    {
                        ErrorMessage += "And more...." + Environment.NewLine;
                        ErrorsCount++;
                    }
                    if (ErrorsCount < maxErrorCount)
                    {
                        ErrorMessage = ErrorMessage + args.Message + Environment.NewLine;
                        ErrorsCount++;
                    }
                    

                    break;
                case XmlSeverityType.Warning:
                    WarningMessage = WarningMessage + args.Message + Environment.NewLine;
                    break;
            }

        }


        public string ValidateSdmxStructure(string tmpXmlFile, EventArgs e)
        {
            XmlDocument tmpDoc = new XmlDocument();
            tmpDoc.Load(tmpXmlFile);

            string appDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
            tmpDoc.Schemas.Add(@"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message", appDir + @"\xsd\SDMXMessage.xsd");
            tmpDoc.Schemas.Add(@"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/structure", appDir + @"\xsd\SDMXStructure.xsd");
            tmpDoc.Schemas.Add(@"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query", appDir + @"\xsd\SDMXQuery.xsd");
            tmpDoc.Schemas.Add(@"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common", appDir + @"\xsd\SDMXCommon.xsd");

            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationHandler);
            ErrorMessage = "";
            ErrorsCount = 0;
            tmpDoc.Validate(eventHandler);

            return ErrorMessage;

        }

    }
}
